package com.iflytek.uoamp.agent.logger.reciver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.apache.log4j.Logger;

/**
 * @ClassName: nettyServer
 * @Description: 日志接收的服务端
 * @author qinanyuan
 * @date 2017年4月5日 上午9:42:59
 */

public class LoggerServer extends Thread {
	private int port;

	public LoggerServer(int port) {
		this.port = port;
		super.setName("LoggerServerThread");
	}

	/**
	 * 启动Netty服务
	 * */
	@Override
	public void run() {
		EventLoopGroup bossGroup = new NioEventLoopGroup(1);
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128)// 构造服务端套接字ServerSocket对象,标识当服务器请求处理线程全满时，用于临时存放已完成三次握手的请求的队列的最大长度
					.option(ChannelOption.TCP_NODELAY, true)// 使消息立即发出去,不用等待到一定的数据量才发出去
					.childOption(ChannelOption.SO_KEEPALIVE, true)// 保持长连接状态
					.handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ChannelPipeline p = ch.pipeline();
							p.addLast(new IdleStateHandler(10, 0, 0));
							p.addLast(new ObjectEncoder());
							p.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
							p.addLast(new LoggerServerHandler());
						}
					});

			// 绑定端口、同步等待
			Channel ch = b.bind(port).sync().channel();
			Logger.getRootLogger().info("server start with port " + port + " success");

			// 等待服务监听端口关闭
			ch.closeFuture().sync();
		} catch (Exception e) {
			Logger.getRootLogger().info("server start with port " + port + " fail, throw exception " + e.getMessage());
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}
